/**
 * @description: 「添加档期」页面，目前用于「主持风采」模块添加档期功能
 * @author: Ruan Jiazhen
 * @date: 2024-03-26 10:14:11
 **/
import { reqAddSchedule } from '@/api/hosting-style';
import { TIME_INTERVAL } from '@/assets/constant/other-constants';
import dayjs from 'dayjs';

let eventChannel: WechatMiniprogram.EventChannel;
Page({
  data: {
    radioIcon: {
      active: '/subpkg/assets/icon/radio-checked.svg',
      normal: '/subpkg/assets/icon/radio.svg',
    },
    checkBoxIcon: {
      active: '/subpkg/assets/icon/check-box-checked.svg',
      normal: '/subpkg/assets/icon/check-box.svg',
    },
    TIME_INTERVAL,
    isShowCustomerInfo: true,
    isShowReceiptStatus: true,
    form: {
      address: '',
      customer_name: '',
      customer_phone: '',
      date: dayjs().format('YYYY-MM-DD'),
      paid: '',
      price: '',
      price_is_settle: '0',
      remark: '',
      schedule_type: '0',
      time_interval: TIME_INTERVAL[0],
    } as CreateScheduleReq,
  },
  onLoad() {
    eventChannel = this.getOpenerEventChannel();
  },
  onScheduleDatePickerChange(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      'form.date': e.detail.date,
      'form.time_interval': e.detail.time_interval,
    });
  },
  async onClickAddress() {
    try {
      const res = await wx.chooseLocation({});
      this.setData({
        'form.address': res.name,
      });
    } catch (e: any) {
      const errMsg = '获取地址失败，请检查网络或定位权限';
      wx.showToast({ title: errMsg, icon: 'none' });
    }
  },
  onChangeFormType(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      'form.schedule_type': e.detail,
    });
  },
  onChangeReceiptStatus(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      'form.price_is_settle': e.detail ? '1' : '0',
    });
  },
  onClickItemTitle(e: WechatMiniprogram.CustomEvent) {
    const showVar = e.currentTarget.dataset.showVar;
    this.setData({
      [showVar]: !this.data[showVar],
    });
  },
  onInput(e: WechatMiniprogram.Input) {
    const key = e.currentTarget.dataset.key;
    this.setData({
      [`form.${key}`]: e.detail.value,
    });
  },
  async onClickSave() {
    try {
      const res = await reqAddSchedule(this.data.form);
      if (res.code !== 200) {
        throw new Error(res.msg);
      }
      wx.showToast({ title: '添加成功' });
      wx.navigateBack();
      eventChannel?.emit('addScheduleSuccess', res.data);
    } catch (e: any) {
      wx.showToast({ title: e.message, icon: 'none' });
      console.error(e);
    }
  },
});
